/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};
*/

class Solution {
public:
    Node* connect(Node* root) {
        queue<Node*> queue;

        if(root != nullptr) queue.push(root);

        Node* lastNode = nullptr;
        Node* currNode = nullptr;
        int size = 0;

        while(queue.empty() == false) {
            size = queue.size();
            lastNode = nullptr;
            for(int i = 0; i < size; ++i){
                currNode = queue.front();
                queue.pop();

                if(lastNode != nullptr) lastNode->next = currNode;
                lastNode = currNode;

                if(currNode->left) queue.push(currNode->left);
                if(currNode->right) queue.push(currNode->right);
            }
        }

        return root;
    }
};